package com.qaml.mes.device;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.cloud.nacos.registry.NacosAutoServiceRegistration;

import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;

import com.qaml.mes.device.api.RbacClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@EnableFeignClients(basePackageClasses = {RbacClient.class})
@SpringBootApplication(scanBasePackages = "com.qaml.mes.device")
@MapperScan(basePackages = "com.qaml.mes.device.dao.mapper")
@EnableScheduling
public class DeviceApplication {


    public static void main(String[] args) {

        SpringApplication.run(DeviceApplication.class, args);
    }

    /**
     * description: 自定义ID主键生成器 <br>
     *
     * @return com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator
     */
    @Bean
    public DefaultIdentifierGenerator defaultIdentifierGenerator() {
        // 以免多线程批量插入，ID主键生成有重复，主键冲突错误
        // 1-31 随机数
        long workerId = RandomUtil.randomLong(1, 31);
        // 1-31 随机数
        long dataCenterId = RandomUtil.randomLong(1, 31);

        return new DefaultIdentifierGenerator(workerId, dataCenterId);
    }


    @ConditionalOnClass(NacosAutoServiceRegistration.class)
    @RestController
    @RequestMapping(value = "actuator")
    @RequiredArgsConstructor
    @Slf4j
    public static class NacosStopEndpoint {

        private static final String SERVER_NAME = "localhost";
        private final NacosAutoServiceRegistration nacosAutoServiceRegistration;

        @DeleteMapping(value = "/deregister/service")
        public ResponseEntity<Boolean> stopNacosService() {
            log.info("ready to stop service ......");
            nacosAutoServiceRegistration.stop();
            log.info("service instance are deregister form nacos");
            return ResponseEntity.ok(true);
        }
    }
}
